﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CodeFarmer
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "GetAuthenCode",
                "image/AuthenCode",
                new { controller = "AuthenCode", action = "Generate" }
                );

            routes.MapRoute(
                "Register",
                "UserCenter/Register",
                new { controller = "UserCenter", action = "Register" }
                );
            routes.MapRoute(
               "Login",
               "UserCenter/Login",
               new { controller = "UserCenter", action = "Login" }
               );

            routes.MapRoute(
                "User",
                "u/{id}",
                new { controller = "UserCenter", action = "GetUser", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                "Article",
                "{author}/archive/{y}/{m}/{d}/{id}",
                new
                {
                    controller = "Article",
                    action = "GetArticle",
                    author = UrlParameter.Optional,
                    id = UrlParameter.Optional
                },
                new { y = @"\d{4}", m = @"\d{2}", d = @"\d{2}" }
            );

            routes.MapRoute(
                "Default",
                "{controller}/{action}", 
                new { controller = "Site", action = "Index"}
            );
        }

        protected void Application_Start()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            CodeFarmer.Controller.BootStrapper.Initialize();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError().InnerException ?? Server.GetLastError();
            string msg = string.Format("\r\nGlobal异常\r\n{0}:  {1}", Request.HttpMethod, Request.Form);
            CodeFarmer.Core.Utility.LogHelper.WriteException(msg, ex);
            HttpContext.Current.ClearError();
        }

    }
}